package com.purple;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermissions;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class FileLogAppender implements LogAppender {
    public final  static  String SUGGESTFILE = "/home/xieweig/document/snapper.log";
//    private String outputFile;
    private RandomAccessFile randomAccessFile;
    public FileLogAppender(String outputFile) {
//        this.outputFile = outputFile;
        try {
            randomAccessFile = new RandomAccessFile(outputFile,"rw");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void append(Object o) {
        try {
            randomAccessFile.seek(randomAccessFile.length());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String k = String.format("[ %s ]: %s",
                LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME),
                o.toString());
        try {
            randomAccessFile.write(k.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close() throws IOException {
        randomAccessFile.close();
    }

    public static void main(String[] args) {
//        good mornings
        String file = "/home/xieweig/document/snapper.log";
        Path  p = Paths.get(file);
        if (Files.notExists(p)){
            try {
                Files.createFile(p, PosixFilePermissions.asFileAttribute(
                        PosixFilePermissions.fromString("rwxrwxr--")
                ));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        LogAppender appender = new FileLogAppender(file);
//        new B(appender);
//        B.
        appender.append("sssss");
    }

}
